<template>
  <div id="searchForm">
    <el-row :gutter="8">
      <el-col :span="19">
        <el-form :model="queryParams" ref="queryParams" size="big" :inline="true" label-width="68px" >
          <el-form-item label="用户名" prop="userName">
            <el-input
                placeholder="请输入搜索用户名 "
                v-model="queryParams.userName"
                style="width: 200px;margin-right: 15px"
                clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="管理员" prop="isAdmin">
            <el-select v-model="queryParams.isAdmin" placeholder="请选择是否为管理员">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button icon="el-icon-search" circle type="success" @click="submitSearch"></el-button>
          <el-button icon="el-icon-refresh-left" circle type="danger" @click="resetQuery"></el-button>
        </el-form>
      </el-col>
    </el-row>
      <div>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户名" align="center" prop="userName" />
          <el-table-column label="密码" align="center" prop="passWord" width="180"/>
          <el-table-column label="管理员权限" align="center" prop="isAdmin">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.isAdmin">管理员</el-tag>
              <el-tag v-if="!scope.row.isAdmin">用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
              >修改</el-button>
              <el-button
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top:20px; padding-bottom: 30px">
          <p style="float: right;height: 31px;line-height: 31px;font-size: 15px; color: #666666">总页数：{{this.pages}}</p>
          <el-pagination
              style="float: right;"
              :current-page.sync="pageNum"
              :page-size="pageSize"
              @current-change="handleCurrentChange"
              layout="total, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </div>
    <el-dialog :title="title" :visible.sync="editOpen" width="400px" :close="resetForm" append-to-body>
      <el-form ref="form" :model="form" :rules="formRule" label-width="85px">
        <el-form-item label="用户密码:" prop="passWord">
          <el-input
              placeholder="密码"
              v-model="form.passWord"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="用户身份:" prop="isAdmin">
          <el-select v-model="form.isAdmin" placeholder="请选择是否为管理员">
            <el-option
                v-for="item in options"
                :key="item.label"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-button type="warning" @click="submitEdit" round>修改</el-button>
        <el-button type="info" @click="editOpen = false" round>取消</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "account",
  data(){
    return{
      /**
       * 查询参数
       */
      queryParams:{
        userName: null,
        isAdmin: null,
      },
      //dialog 是否打开
      editOpen: false,
      form:{
        userName: null,
        passWord: null,
        isAdmin: false,
      },
      formRule:{
        userName: [
          { required: true, trigger: 'blur' , message: '请输入用户名'},
          {
            required: true,
            pattern: /^[1-9]{1}[0-9]{4,9}$/,
            message: '用户账户首位应为1~9的数字，只允许纯数字用户名！长度在 4 到 10 位',
            trigger: 'blur'
          }
        ],
        passWord: [
          { required: true, trigger: 'blur' , message: '请输入密码'},
          {
            required: true,
            pattern: /^[a-zA-Z][a-zA-Z0-9_]{7,15}$/,
            message: '需首位包含字母，长度在 8 到 15 位！',
            trigger: 'blur'
          }
        ],
      },
      title: '设置账号信息',
      userList: null,
      //页数
      pages: 1,
      //当前页
      pageNum: 1,
      //每页限制数据
      pageSize: 1,
      //总条目数
      total: 1,
      loading: false,
      options:[
        {label: '管理员', value: true},
        {label: '用户', value: false},
      ],
    }
  },
  created() {
    this.getList();
  },
  inject: ["refreshAdmin","setComponent"],
  methods:{
    getList() {
      this.loading = true;
      axios.get('api/account/list', {
        params:{
          userName: this.queryParams.userName,
          isAdmin: this.queryParams.isAdmin,
          pageNum: this.pageNum,
        }
      }).then( res =>{
        if(res.data.responseCode === 200){
          this.userList = res.data.objectResult.list;
          this.total = res.data.objectResult.total;
          this.pages = res.data.objectResult.pages;
          this.pageSize = res.data.objectResult.pageSize;
          this.pageNum = res.data.objectResult.pageNum;
          this.loading = false;
        }
        else{
          this.$notify({
            title: '获取失败',
            message: res.data.message,
            duration: 3000,
            type: 'warning',
          });
          this.loading = false;
        }
        this.refreshAdmin();
        this.editOpen = false;
      }).catch(err=>{
        this.$notify({
          title: '获取失败',
          message: "服务器错误，"+err.message,
          duration: 3000,
          type: 'warning',
        });
        this.loading = false;
      })
    },
    /**
     * 提交表单
     */
    submitSearch(){
      this.getList();
    },
    /**
     * 重置表单
     */
    resetQuery(){
      this.queryParams = {
        userName: null,
        isAdmin: null,
      }
      this.getList()
    },
    resetForm(){
      this.form = {
        passWord: null,
        isAdmin: null,
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /**
     * 进行账号修改
     */
    handleEdit(row){
      console.log(row);
      this.editOpen = true
      this.form.userName = row.userName
      this.form.passWord = row.passWord;
      this.form.isAdmin = row.isAdmin;
    },
    /**
     * 提交菜单
     */
    submitEdit(){
      this.$refs.form.validate((valid) => {
        if(valid){
          axios.post("api/account/edit",this.form).then(res => {
            if(res.data.responseCode === 200){
              if(this.$cookies.get("admin") === "false"){
                this.setComponent("fileIO")
              }
              if(this.$cookies.get("token") === "false"){
                this.$message({
                  type: 'warning',
                  message: '您已更改密码，请重新登录！'
                });
                this.$cookies.remove("token")
                this.$router.push({path:'/'})
                return;
              }
              this.$message({
                type: 'success',
                message: res.data.message
              });
            }else{
              this.$message({
                type: 'warning',
                message: res.data.message
              });
              console.log(this.$cookies.get("admin"))
              if(this.$cookies.get("admin") === "false"){
                this.setComponent("fileIO")
              }
              if(this.$cookies.get("token") === "false"){
                console.log("change passowrd")
                this.$cookies.remove("token")
                this.$router.push({path:'/'})
              }
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err.message
            })
          })
          this.refreshAdmin();
          this.getList();
          this.editOpen = false;
        }
      });
    },
    reload(){
      this.isRouterAlive = false;
      this.$nextTick(function () {
        this.isRouterAlive = true;
      });
    },
    /**
     * 删除操作
     */
    handleDelete(row){
      this.form.userName = row.userName
      this.form.passWord = row.passWord;
      this.form.isAdmin = row.isAdmin;
      this.$confirm('此操作将永久删除该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('api/account/delete',this.form).then(res =>{
          if(res.data.responseCode === 200){
            this.$message({
              type: 'success',
              message: res.data.message
            });
          }else {
            this.$message({
              type: 'success',
              message: res.data.message
            });
            if(res.data.objectResult != null){
              this.$cookies.remove("token")
              this.$router.push({path:'/'})
            }
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err.message
          });
        });
      })
    },
    /**
     * 当前页修改
     */
    handleCurrentChange(val){
      this.pageNum = val;
      this.getList()
    }
  }
}
</script>

<style scoped>

</style>